Skip to content

CommandPalette

Base classes

Name Children Inherits
Widget
prettyqt.widgets.widget
The base class of all user interface objects.

â‹” Inheritance diagram

graph TD
  1533692102["custom_widgets.CommandPalette"]
  3664736470["widgets.Widget"]
  829357528["widgets.WidgetMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  625385617["gui.PaintDeviceMixin"]
  3620195106["QtWidgets.QWidget"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  673956333["QtGui.QPaintDevice"]
  3664736470 --> 1533692102
  829357528 --> 3664736470
  3227531497 --> 829357528
  2751680898 --> 3227531497
  625385617 --> 829357528
  2751680898 --> 625385617
  2751680898 --> 829357528
  3620195106 --> 3664736470
  3984060476 --> 3620195106
  37984305 --> 3984060476
  2751680898 --> 37984305
  673956333 --> 3620195106
  37984305 --> 673956333

🛈 DocStrings

Bases: Widget

A Qt command palette widget.

Source code in prettyqt/custom_widgets/commandpalette.py
class CommandPalette(widgets.Widget):
    """A Qt command palette widget."""

    def __init__(self, parent: widgets.QWidget | None = None):
        super().__init__(parent=parent)
        self.setWindowFlags(
            constants.WindowType.WindowStaysOnTopHint
            | constants.WindowType.FramelessWindowHint
            # | constants.WindowType.ToolTip
        )
        self.setAutoFillBackground(True)
        self.setAttribute(constants.WidgetAttribute.WA_StyledBackground, True)
        self.set_focus_policy("strong")
        self.setMinimumWidth(420)
        self._line = widgets.LineEdit()
        self.setFocusProxy(self._line)
        self._table = CommandTable()
        # self._line.value_changed.connect(self._table.select_first_row)
        self._line.value_changed.connect(self._table._proxy.set_search_term)
        self._table.action_clicked.connect(self.hide)
        layout = self.set_layout("vertical")
        layout.addWidget(self._line)
        layout.addWidget(self._table)
        self.add_shortcut("Ctrl+P", callback=self.close)
        self._line.installEventFilter(self)

        # self._line.textChanged.connect(self._on_text_changed)
        # self._table.action_clicked.connect(self._on_action_clicked)
        # self._line.editingFinished.connect(self.hide)

    def eventFilter(self, source: core.QObject, e: core.QEvent) -> bool:
        if (
            source != self._line
            or e.type() != core.QEvent.Type.KeyPress
            or not isinstance(e, gui.QKeyEvent)
        ):
            return super().eventFilter(source, e)
        if e.modifiers() in (
            constants.KeyboardModifier.NoModifier,
            constants.KeyboardModifier.KeypadModifier,
        ):
            match e.key():
                case constants.Key.Key_Escape:
                    self.hide()
                    return True
                case constants.Key.Key_Return:
                    self.hide()
                    self._table.execute_focused()
                    return True
                case constants.Key.Key_Up:
                    self._table.move_row_selection(-1)
                    return True
                case constants.Key.Key_Down:
                    self._table.move_row_selection(1)
                    return True
        return super().eventFilter(source, e)

    def populate_from_widget(self, widget: widgets.QWidget):
        self.add_actions(widget.actions())
        if not callable(widget.parent):
            return
        obj: core.QObject | None = widget
        while (obj := obj.parent()) is not None:
            if isinstance(obj, widgets.QWidget):
                self.add_actions(obj.actions())

    def add_path_actions(self, path):
        path = pathlib.Path(path)
        actions = [gui.Action(str(p)) for p in path.rglob("*") if p.is_file()]
        self.add_actions(actions)

    def match_color(self) -> str:
        """The color used for the matched characters."""
        return self._table._proxy.get_match_color().name()

    def set_match_color(self, color: datatypes.ColorType):
        """Set the color used for the matched characters."""
        self._table._proxy.set_match_color(colors.get_color(color))

    def install_to(self, parent: widgets.QWidget):
        self.setParent(parent, constants.WindowType.SubWindow)
        self.hide()

    # def focusOutEvent(self, a0: gui.QFocusEvent) -> None:
    #     self.hide()
    #     return super().focusOutEvent(a0)

    def add_actions(self, actions: Iterable[gui.QAction]):
        """Append actions to the palette."""
        self._table._model.add_items(actions)

    def set_actions(self, actions: Iterable[gui.QAction]):
        """Replace all actions of the palette (also refreshes changed action texts)."""
        self._table._model.set_list(list(actions))

    def get_actions(self) -> list[gui.QAction]:
        """Return the actions of the palette."""
        return list(self._table._model.items)

    def clear(self):
        """Remove all actions from the palette."""
        self.set_actions([])

    def show(self):
        self._line.setText("")
        parent = self.parentWidget()
        if parent is not None and self.windowType() == constants.WindowType.SubWindow:
            width = min(680, max(420, parent.width() - 80))
            height = min(380, max(240, parent.height() - 120))
            x = max(12, (parent.width() - width) // 2)
            y = max(36, int(parent.height() * 0.12))
            self.setGeometry(x, y, width, height)
        else:
            self.resize(1000, 300)
            self.position_on("screen")
        super().show()
        self.raise_()
        self._line.setFocus()

add_actions(actions: Iterable[gui.QAction])

Append actions to the palette.

Source code in prettyqt/custom_widgets/commandpalette.py
def add_actions(self, actions: Iterable[gui.QAction]):
    """Append actions to the palette."""
    self._table._model.add_items(actions)

clear()

Remove all actions from the palette.

Source code in prettyqt/custom_widgets/commandpalette.py
def clear(self):
    """Remove all actions from the palette."""
    self.set_actions([])

get_actions() -> list[gui.QAction]

Return the actions of the palette.

Source code in prettyqt/custom_widgets/commandpalette.py
def get_actions(self) -> list[gui.QAction]:
    """Return the actions of the palette."""
    return list(self._table._model.items)

match_color() -> str

The color used for the matched characters.

Source code in prettyqt/custom_widgets/commandpalette.py
def match_color(self) -> str:
    """The color used for the matched characters."""
    return self._table._proxy.get_match_color().name()

set_actions(actions: Iterable[gui.QAction])

Replace all actions of the palette (also refreshes changed action texts).

Source code in prettyqt/custom_widgets/commandpalette.py
def set_actions(self, actions: Iterable[gui.QAction]):
    """Replace all actions of the palette (also refreshes changed action texts)."""
    self._table._model.set_list(list(actions))

set_match_color(color: datatypes.ColorType)

Set the color used for the matched characters.

Source code in prettyqt/custom_widgets/commandpalette.py
def set_match_color(self, color: datatypes.ColorType):
    """Set the color used for the matched characters."""
    self._table._proxy.set_match_color(colors.get_color(color))

:fa-brands-github: Show source on GitHub